//=============================================================================
// System  : MatchKit
// File    : ObjectReplacer.cs
// Author  : Fabio Bussu  (matchkit@fabiobussu.it)
// Updated : 04/16/2013
// Note    : Copyright 2013, Fabio Bussu, All rights reserved
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code.  It can also be found
// at the project website: http://matchkit.codeplex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version     Date     Who  Comments
// ============================================================================
// 1.0.0.0  04/16/2013   FB  First draft
//=============================================================================
using System;
using System.Collections.Generic;
#if EX
using System.Linq.Expressions;
#endif
using System.Reflection;
using System.Text;

namespace MatchKit.ObjectMapping
{
	/// <summary>
	/// Provides the ability to replace a string matched with a mapping operation and 
	/// filled match bag.
	/// </summary>
	/// <threadsafety static="true" instance="false" />
	/// <serialization binary="true" contract="false" />
	/// <conceptualLink target="7e345cd8-5aaa-4616-a3c9-ab0aaa44dabc" />
	/// <conceptualLink target="0a06b2a9-5f58-409a-ba62-639cfd77bca7" />
	public sealed class ObjectReplacer
	{
		sealed class Entry
		{
			public object Instance;
			public object NewValue;
		}

		private string _targetText;
		private IMatchBag _mbag;
		private Dictionary<MemberInfo, Entry> _entries = new Dictionary<MemberInfo, Entry>();

		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.ObjectReplacer"/> class.
		/// </summary>
		/// <param name="targetText">Text to replace.</param>
		/// <param name="matchBag">Match bag previously filled with mapping operation.</param>
		public ObjectReplacer(string targetText, IMatchBag matchBag)
		{
			if (targetText == null)
				throw new ArgumentNullException("targetText", "targetText cannot be null");
			if (matchBag == null)
				throw new ArgumentNullException("matchBag", "matchBag cannot be null");

			_targetText = targetText;
			_mbag = matchBag;
		}

		#if EX
		/// <summary>
		/// Registers a replace to be applied with <see cref="M:MatchKit.ObjectReplacer.Apply"/> method.
		/// </summary>
		/// <typeparam name="TInstance">Type of the instance to be replaced.</typeparam>
		/// <typeparam name="TMember">Type of the member to be replaced.</typeparam>
		/// <param name="instance">Instance declaring the member to be replaced. This value cannot be null.</param>
		/// <param name="memberReference">Expression that references the matchable field or property to be replace. This value cannot be null.</param>
		/// <param name="newValue">Value to replace.</param>
		public void Replace<TInstance, TMember>(TInstance instance, Expression<Func<TInstance, TMember>> memberReference, TMember newValue)
		{
			if (instance == null)
				throw new ArgumentNullException("instance", "instance cannot be null");
			if (memberReference == null)
				throw new ArgumentNullException("memberReference", "memberReference cannot be null");

			var body = memberReference.Body;
			var memberExpr = body as MemberExpression;

			if (memberExpr == null)
				throw new ArgumentException("memberReference must contains a MemberExpression body", "memberReference");

			if (memberExpr.Member.GetAttribute<MatchableMemberAttribute>() == null)
				throw new ArgumentException("memberReference must reference a matchable member", "memberReference");

			var field = memberExpr.Member as FieldInfo;
			var property = memberExpr.Member as PropertyInfo;

			if (field == null && property == null)
				throw new ArgumentException("body must reference a field or a property", "body");

			_entries[memberExpr.Member] = new Entry { Instance = instance, NewValue = newValue };
		}
		#endif

		/// <summary>
		/// Registers a replace to be applied with <see cref="M:MatchKit.ObjectReplacer.Apply"/> method.
		/// </summary>
		/// <param name="instance">Instance declaring the member to be replaced. This value cannot be null.</param>
		/// <param name="memberName">Name of the matchable field or property to be replace. This value cannot be null.</param>
		/// <param name="newValue">Value to replace.</param>
		public void Replace(object instance, string memberName, object newValue)
		{
			if (instance == null)
				throw new ArgumentNullException("instance", "instance cannot be null");
			if (memberName == null)
				throw new ArgumentNullException("memberName", "memberName cannot be null");

			var type = instance.GetType();
			var members = type.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public 
				| BindingFlags.NonPublic | BindingFlags.Static);

			if (members == null || members.Length == 0)
				throw new ArgumentException("memberName reference an invalid member", "memberName");

			_entries[members[0]] = new Entry { Instance = instance, NewValue = newValue };
		}

		/// <summary>
		/// Registers a replace to be applied with <see cref="M:MatchKit.ObjectReplacer.Apply"/> method.
		/// </summary>
		/// <param name="instance">Instance declaring the member to be replaced. This value cannot be null.</param>
		/// <param name="member">Reflection member info of the matchable field or property to be replace. This value cannot be null.</param>
		/// <param name="newValue">Value to replace.</param>
		public void Replace(object instance, MemberInfo member, object newValue)
		{
			if (instance == null)
				throw new ArgumentNullException("instance", "instance cannot be null");
			if (member == null)
				throw new ArgumentNullException("member", "member cannot be null");

			_entries[member] = new Entry { Instance = instance, NewValue = newValue };
		}

		sealed class MatchEntry
		{
			public Match Match;
			public Entry Entry;
			public MatchEntry(Match match, Entry entry)
			{
				Match = match;
				Entry = entry;
			}
		}

		/// <summary>
		/// Performs the replacements previously registered with <b>Replaces</b> methods.
		/// </summary>
		/// <returns>The replaced string.</returns>
		public string Apply()
		{
			var sb = new StringBuilder(_targetText.Length);
			int lastIndex = 0;
			var matches = new List<MatchEntry>(_entries.Count);

			foreach (var entry in _entries)
				matches.Add(new MatchEntry(_mbag.GetMatch(entry.Value.Instance, entry.Key), entry.Value));

			matches.Sort((a, b) => a.Match.Location.Index.CompareTo(b.Match.Location.Index));

			foreach (var tuple in matches)
			{
				var m = tuple.Match;
				var e = tuple.Entry;

				var loc = m.Location;
				sb.Append(_targetText.Substring(lastIndex, loc.Index - lastIndex));
				if (e.NewValue != null)
					sb.Append(e.NewValue.ToString());
				lastIndex = loc.Index + m.MatchLength;
			}

			sb.Append(_targetText.Substring(lastIndex, _targetText.Length - lastIndex));

			return sb.ToString();
		}
	}
}
